package com.xiaohei.auth.service.impl;

import com.xiaohei.auth.service.SysMenuService;
import com.xiaohei.auth.service.SysUserService;
import com.xiaohei.common.config.exception.XiaoheiException;
import com.xiaohei.common.result.ResultCodeEnum;
import com.xiaohei.model.system.SysUser;
import com.xiaohei.security.custom.CustomUser;
import com.xiaohei.security.custom.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * ClassName: UserDetailsServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/5/1 18:31
 * Version 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 根据用户名获取用户对象（获取不到直接抛异常）
     *
     * @param username
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名进行查询
        SysUser sysUser = sysUserService.getUserByUsername(username);

        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new XiaoheiException(ResultCodeEnum.ACCOUNT_STOP);
        }

        //根据用户id查询用户操作的权限数据
        List<String> userPermsList = sysMenuService.findMenuPermsByUserId(sysUser.getId());
        //创建一个List集合用于封装最终权限数据
        List<SimpleGrantedAuthority>  authList = new ArrayList<SimpleGrantedAuthority>();
        //查询list集合遍历
        for(String perm : userPermsList){
            authList.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return new CustomUser(sysUser, authList);
    }
}
